package com.hulman.oms.web;

import com.hulman.oms.bean.Result;
import com.hulman.oms.exception.IoTException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * @Author: maxwellens
 */
@RestControllerAdvice
@Slf4j
public class RestApiControllerAdvice
{
    @ExceptionHandler(value = Exception.class)
    public Result exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception ex)
    {
        log.error("exceptionHandler:",ex);
        if (ex instanceof IoTException)
        {
            Integer code = ((IoTException) ex).getCode();
            response.setStatus(Result.CODE_SUCCESS);
            IoTException iotException = ((IoTException) ex);
            return new Result(code, iotException.getMessage(), iotException.getExtra());
        } else
        {
            response.setStatus(Result.CODE_SUCCESS);
            return new Result(Result.CODE_SERVER_ERROR, ex.getMessage(), null);
        }

    }

    @ModelAttribute
    public void addAttributes(Model model)
    {

    }

    @InitBinder
    public void initBinder(WebDataBinder binder)
    {

    }
}
